<template>
  <el-select
    v-model="inputValue"
    :placeholder="`请选择${field.displayName}`"
    :disabled="disabled"
    @change="handleChange"
    clearable
  >
    <el-option
      v-for="option in options"
      :key="option.value"
      :label="option.label"
      :value="option.value"
    ></el-option>
  </el-select>
</template>

<script setup>
import { ref, watch, computed } from 'vue'

const props = defineProps({
  field: {
    type: Object,
    required: true
  },
  value: {
    type: [String, Number],
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['input', 'change'])

const inputValue = ref(props.value)

// 解析选项
const options = computed(() => {
  if (props.field.options && typeof props.field.options === 'string') {
    try {
      const parsed = JSON.parse(props.field.options)
      return parsed.options || []
    } catch (e) {
      console.error('解析选项失败:', e)
      return []
    }
  } else if (props.field.options && props.field.options.options) {
    return props.field.options.options
  }
  return []
})

// 监听值变化
watch(() => props.value, (newVal) => {
  inputValue.value = newVal
})

// 处理变化
const handleChange = (val) => {
  emit('input', val)
  emit('change')
}
</script>
